#include <stdio.h>
#include <stdlib.h>

//开始->定义链表头指针->尾插法新建链表->查找某个位置的元素值(需要判断该位置是否合法,L是位置0)->遍历链表查找值->结束
typedef int ElemType;
typedef struct LNode {
    ElemType data;
    LNode *next;
} LNode, *LinkList;

void List_head_insert(LinkList &L) {
    L = (LinkList) malloc(sizeof(LNode));//申请头指针
    ElemType num;
    LinkList q, p;
    q = L;//将头结点的位置赋给头指针
    scanf("%d", &num);
    while (num != 9999) {
        p = (LinkList) malloc(sizeof(LNode));
        p->data = num;
        q->next = p;//将新结点的位置赋给尾结点的next指针
        q = p;//将指针地址赋给下一个指针
        scanf("%d", &num);
    }
    p->next = NULL;//将尾指针的数据域置为NULL
}

//链表输出
void Print_list(LinkList L) {
    L = L->next;
    while (L) {
        printf("%3d ", L->data);
        L = L->next;
    }
}

//按位置查找及按值查找
//开始->定义链表头指针->尾插法新建链表->查找某个位置的元素值(需要判断该位置是否合法,L是位置0)->遍历链表查找值->结束

//按位置查找
LinkList GetElem(LinkList L, ElemType pos) {
    int i = 0;
    if (pos < 0) return NULL;
    //以下式子可写为while(L&&!<pos)
    while (L != NULL && i < pos) {
        L = L->next;
        i++;
    }
    return L;
}
//按值查找
LinkList LocateElem(LinkList L, ElemType value) {
    for (; L; L = L->next) {
        if (value == L->data) {
            return L;
        }
    }
    return NULL;
}

int main() {
    LinkList L;//定义链表头指针(结构体指针类型)
    LinkList search;//用来存储拿到的某一个节点
    List_head_insert(L);
    Print_list(L);//链表打印
    //按位置查找
    search = GetElem(L, 5);
    if (search != NULL) {
        //serial number:编号,序号
        printf("\nSucceeded in searching by serial number\n");
        printf("%3d", search->data);
    }
    //按值查找
    search = LocateElem(L, 0);
    if (search != NULL) {
        printf("\nSearch by value succeed\n");
        printf("%3d", search->data);
    }else{
        printf("\ncan't find the number you want to find");
    }
    return 0;
}
